package controllers;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.BeanLogin;
import models.User;

import utils.BeanUtilities;
import utils.DAOUser;

/**
 * Servlet implementation class LoginController
 */
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession(true);

		try {
			String user = (String) request.getParameter("user");
			BeanLogin loginBean = new BeanLogin();
			BeanUtilities.populateBean(loginBean, request);
			if (loginBean.userCorrect()) {
				DAOUser daoUser = new DAOUser();
				synchronized (session) {
					if (daoUser.isAdmin(user))
						session.setAttribute("isAdmin", "true");
					session.setAttribute("user", user);

					session.setAttribute("contentView", "TweetController");
					User currentUser = daoUser.getUser(user);
					daoUser.setAcceptedContact(currentUser, user);
					daoUser.setContact(currentUser, user);
					daoUser.setFollower(currentUser, user);
					session.setAttribute("currentUser", currentUser);
				}
				response.sendRedirect("HomeController");

			} else {
				request.setAttribute("login", loginBean);
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("/index.jsp");
				if (dispatcher != null)
					dispatcher.forward(request, response);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect("blank.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
